<?php
/**
 * ClassName: CardService
 * Description:
 * @Author 周昌
 * @Create 2023/11/16 10:18
 */

namespace service\admin;


use libs\Tool;
use model\CardCateModel;
use model\MemberModel;
use service\BaseService;
use think\Db;

class CardService extends BaseService
{
    protected static $model='model\CardModel';

    //会员卡充值+增加卡充值记录
    public static function cardRecharge($where,$recharge_money,$gift_money)
    {
        $money=bcadd($recharge_money,$gift_money);
        Db::startTrans();
        try {
            //使用行锁锁定该行数据
            $res=self::$model::where($where)->lock(true)->find();
            $result=self::$model::where($where)->setInc('money',$money);
            if ($result===false){
                Db::rollback();
                return Tool::Error('卡充值失败');
            }
            $log_insert=[
                'member_id'=>$res['member_id'],
                'card_id'=>$res['id'],
                'card_cate_id'=>$res['card_cate_id'],
                'money'=>$recharge_money,
            ];
            $log_res=CardLogService::addCardLog(CardLogService::$card_log_type_index['recharge'],$log_insert,null,$gift_money);
            if($log_res['code']==0){
                Db::rollback();
                return Tool::Error('添加卡充值记录失败');
            }
            //充值消息
            $message_res=MessageService::addMessage($res['member_id'],MessageService::$message_type_index['recharge'],$recharge_money,$res['id'],null,$gift_money);
            if($message_res['code']==0){
                Db::rollback();
                return Tool::Error('卡充值消息添加失败');
            }
            //分段充值+消费记录表
            $recharge_insert=[
                'card_id'=>$res['id'],
                'money'=>$recharge_money,
                'gift_money'=>$gift_money,
                'addtime'=>time(),
            ];
            $card_recharge=CardRechargeService::add($recharge_insert);
            if($card_recharge['code']==0){
                Db::rollback();
                return Tool::Error('分段充值/消费记录添加失败');
            }
            Db::commit();
            return Tool::Success('充值成功');
        }catch (\Exception $exception){
            Db::rollback();
            return Tool::Error($exception->getMessage());
        }
    }

    /**
     * #User: Administrator
     * #Time: 2024/1/17 11:16
     * #Author:周昌
     * #Description: 会员卡消费+消费记录
     * @param $where array card表where条件 锁定一条card数据
     * @param $money float 消费金额
     * @param $log_insert array 消费记录数据 包括：'type','member_id','member_info_id','card_id'
     * ,'money','case_id'
     * @return array
     */
    public static function cardConsume($where,$money,$log_insert)
    {
        Db::startTrans();
        try {
            //使用行锁锁定该行数据
            $res=self::$model::where($where)->lock(true)->find();
            if($res['money']<$money){
                Db::rollback();
                return Tool::Error('卡余额不足');
            }
            $result=self::$model::where($where)->setDec('money',$money);
            if ($result===false){
                Db::rollback();
                return Tool::Error('卡消费失败');
            }
            //分段消费
            $card_recharge=CardRechargeService::consume($res['id'],$money);
            if($card_recharge['code']==0){
                Db::rollback();
                return Tool::Error('分段消费更新失败');
            }
            //消费记录增加 消费真充金额+消费=赠送金额
            $log_insert['pay_money']=$card_recharge['data']['seed_money'];
            $log_insert['pay_gift']=$card_recharge['data']['gift_money'];
            $log_insert['card_cate_id']=$res['card_cate_id'];

            $case_id=$log_insert['case_id'];
            unset($log_insert['case_id']);
            $card_log=CardLogService::addCardLog($log_insert['type'],$log_insert,$case_id);
            if($card_log['code']==0){
                Db::rollback();
                return Tool::Error('卡消费记录添加失败');
            }
            Db::commit();
            return Tool::Success('卡消费成功');
        }catch (\Exception $exception){
            Db::rollback();
            return Tool::Error($exception->getMessage());
        }
    }
    /**
     * #User: Administrator
     * #Time: 2024/1/9 14:54
     * #Author:周昌
     * #Description: 获取会员办理的 会员卡列表
     * @param $member_id
     * @param null $user_limit 卡的使用范围 0=>'诊疗',1=>'不限'
     * @return array
     */
    public static function getCardList($member_id,$user_limit=null)
    {
        $data=[];
        $where=[
            'member_id'=>$member_id,
            'status'=>1,
            'hospital_group_id'=>self::getUserHospitalGroupId()
        ];
        $list=self::$model::getList($where,'id,card_cate_id,money');
        if(!empty($list)){
            $card_cate_ids=array_column($list,'card_cate_id');
            $cate_where=[
                ['id','in',$card_cate_ids],
            ];
            //根据卡的使用范围进行筛选
            if(!is_null($user_limit)){
                $cate_where[]=['use_limit','=',$user_limit];
            }

            $card_cate_info=CardCateModel::getListColumn($cate_where,'id,name');
            foreach ($list as $k=>$v){
                if(isset($card_cate_info[$v['card_cate_id']])){
                    $row=[];
                    $row['id']=$v['id'];
                    $row['name']=$card_cate_info[$v['card_cate_id']].'-'.$v['money'];
                    $data[]=$row;
                }
            }
            array_unshift($data,['id'=>'','name'=>'-----请选择会员卡-----']);
        }
        return $data;
    }

    //添加，编辑
    public static function addEdit($data,$id)
    {
        $mem_info=MemberModel::getInfo(['phone'=>$data['phone']],'id,real_name,sex');
        $data['money']=bcadd($data['recharge_money'],$data['gift_money']);
        $recharge_money=$data['recharge_money'];
        $gift_money=$data['gift_money'];
        unset($data['recharge_money']);
        unset($data['gift_money']);

        if ($id) {
            $data['member_id']=$mem_info['id'];
            unset($data['money']);
            $res = CardService::edit($id,$data);
            return $res;
        } else {
            Db::startTrans();
            try {
                if(!$mem_info){
                    //注册
                    $insert=[
                        'phone'=>$data['phone'],
                        'real_name'=>$data['real_name'],
                        'sex'=>$data['sex'],
                        'hospital_id'=>self::getUserHospitalId(),
                        'addtime'=>time(),
                    ];
                    $m_res=MemberService::addMemberAndInfo($insert);
                    if($m_res['code']){
                        $data['member_id']=$m_res['data']['member_id'];
                    }else{
                        Db::rollback();
                        return Tool::Error('新增用户失败');
                    }
                }else{
                    $data['member_id']=$mem_info['id'];
                }
                $data['addtime']=time();
                $res = CardService::add($data);
                if(!$res['code']){
                    Db::rollback();
                    return Tool::Error('新增用卡失败');
                }
                //添加card_log 记录
                if($data['money']>0){
                    $log_insert=[
                        'member_id'=>$data['member_id'],
                        'card_id'=>$res['data']['id'],
                        'card_cate_id'=>$data['card_cate_id'],
                        'money'=>$recharge_money,
                    ];
                    $log_res=CardLogService::addCardLog(CardLogService::$card_log_type_index['recharge'],$log_insert,null,$gift_money);
                    if($log_res['code']==0){
                        Db::rollback();
                        return Tool::Error('添加卡充值记录失败');
                    }
                    //充值消息
                    $message_res=MessageService::addMessage($data['member_id'],MessageService::$message_type_index['recharge'],$recharge_money,$res['data']['id'],null,$gift_money);
                    if($message_res['code']==0){
                        Db::rollback();
                        return Tool::Error('卡充值消息添加失败');
                    }
                    //分段充值+消费记录表
                    $recharge_insert=[
                        'card_id'=>$res['data']['id'],
                        'money'=>$recharge_money,
                        'gift_money'=>$gift_money,
                        'addtime'=>time(),
                    ];
                    $card_recharge=CardRechargeService::add($recharge_insert);
                    if($card_recharge['code']==0){
                        Db::rollback();
                        return Tool::Error('分段充值/消费记录添加失败');
                    }
                }
                //全部成功提交事务
                Db::commit();
               return Tool::Success();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return Tool::Error($e->getMessage());
            }

        }
    }
    //列表数据
    public static function getAjaxData($where)
    {
        $table = self::$model::order('id desc');
        $adminInfo=self::getAdminInfo();
        return self::tableJsonData($table, $where, function ($data)use ($adminInfo){
            //超级管理员获取全部分类，医院管理员获取本院分类
            if($adminInfo['role']==1){
                $data['card_cate_name'] = CardCateService::getNameByKey($data['card_cate_id']);
            }else{
                $data['card_cate_name'] = CardCateService::getNameByKey($data['card_cate_id'],['hospital_group_id'=>$adminInfo['hospital_group_id']]);
            }
            $data['hospital_name'] = $data['hospital_id']?HospitalService::getNameByKey($data['hospital_id'],'','id,name','id','hospital_key_name'):'';
            return $data;
        },function ($data){
            if(!empty($data)){
                $ids=array_column($data,'id');
                $result=CardRechargeService::getMoney($ids);
                foreach ($data as $k=>$v){
                    $data[$k]['recharge_money']=$result[$v['id']]['recharge_money']??'';
                    $data[$k]['gift_money']=$result[$v['id']]['gift_money']??'';
                }
            }
            return $data;
        });
    }
}